package com.origin.niuke.array;

import java.util.ArrayList;
import java.util.List;

/**
 * NC222 插入区间
 * 算法：模拟
 *
 * @author yezh
 * @date 2022/11/26 11:57
 */
public class NC222 {

    public static class Interval {
        int start;
        int end;

        public Interval(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }

    public Interval[] insertInterval(Interval[] intervals, Interval newInterval) {
        // write code here
        int n = intervals.length;
        if (n == 0 || newInterval.end <= intervals[0].start && newInterval.start >= intervals[n - 1].end)
            return new Interval[]{newInterval};
        List<Interval> ans = new ArrayList<>();
        for (Interval interval : intervals) {
            if (newInterval.end < interval.start) {
                ans.add(newInterval);
                newInterval = interval;
            } else if (newInterval.start > interval.end) ans.add(interval);
            else {
                // 有重叠
                newInterval.start = Math.min(newInterval.start, interval.start);
                newInterval.end = Math.max(newInterval.end, interval.end);
            }
        }
        ans.add(newInterval);
        return ans.toArray(new Interval[0]);
    }

}
